package org.argetr.resim.proc.data;

import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.awt.image.renderable.ParameterBlock;

import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import javax.media.jai.TiledImage;


public class ImageDA extends Data {
	protected boolean _writable = false;
	public ImageDA (PlanarImage img) {
		setDataType(Data.IMAGE);
		setData(img);
	}
	public ImageDA (ImageDA imgDA) {
		setDataType(Data.IMAGE);
		TiledImage im = new TiledImage(imgDA.getImage(), true);
		setData(im);
	}
	public PlanarImage getImage(){
		return (PlanarImage) getData();
	}
	public int getNBands(){
		return ((PlanarImage)getData()).getNumBands();
	}
	public int getWidth(){
		return getImage().getWidth();
	}
	public int getHeight(){
		return getImage().getHeight();
	}
	public void setWritable(){
		if(!_writable){
			ParameterBlock pbConvert = new ParameterBlock();
			pbConvert.addSource(getImage());
			pbConvert.add(DataBuffer.TYPE_FLOAT);
			PlanarImage i = (PlanarImage) JAI.create("format", pbConvert);
			TiledImage im = new TiledImage(i, true);
			setData(im);
			_writable = true;
		}
	}
    public double [] getPixelsDouble(){
    	int len = getNBands() * getWidth() * getHeight();
    	double [] pixels = new double [len];
    	Raster inputRaster = getImage().getData();
    	inputRaster.getPixels(0, 0, getWidth(), getHeight(), pixels);
    	return pixels;
    }
    public void setPixelsDouble(double [] pixels){
    	WritableRaster raster = getImage().getData().createCompatibleWritableRaster();
    	raster.setPixels(0, 0, getWidth(), getHeight(), pixels);
    	TiledImage ti = new TiledImage(getImage(), 1, 1);
    	ti.setData(raster);
    	setData(ti);
    }
}
